package com.stylefeng.guns.rest.common.aop;

import com.stylefeng.guns.common.dto.common.ResultData;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.exception.GunsExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author carloszhang
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResultData systemError(Exception e) {
        if (e instanceof GunsException) {
            GunsException gex = (GunsException) e;
            log.error("业务异常:", e);
            return ResultData.errorResult(gex.getCode(), gex.getMessage());
        }

        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException gex = (MethodArgumentNotValidException) e;
            log.error("请求参数异常:", e);
            return ResultData.errorResult(BizExceptionEnum.REQUEST_NULL.getCode(), gex.getMessage());
        }

        if (e instanceof RuntimeException) {
            log.error("运行时异常:", e);
            return ResultData.errorResult(BizExceptionEnum.SYSTEM_ERROR.getCode(), BizExceptionEnum.SYSTEM_ERROR.getMessage());
        }
        log.error("其他异常:", e);
        return ResultData.errorResult(BizExceptionEnum.SYSTEM_ERROR.getCode(), "系统错误");
    }

}
